<template>
  <router-view></router-view>
</template>

<script setup lang="ts">
import {getTokenAtStorage, setRefreshTokenAtStorage, setTokenAtStorage} from './utils/tokens.js'
import {useChatStore} from "./stores/chating_store.ts";
import {useContactStore} from "./stores/contacts_store.ts";
import {useLoginStore} from './stores/login_store.ts'
import LoginApi from './api/login.js';
import UserApi from './api/user.js';
import {useWebSocket} from '@/models/useWebSocket.js';
import {SignalWS} from '@/models/call_service.ts';

import {provide} from "vue";
import {useRouter} from "vue-router";
import {ChatMessage, E_Action, MsgEvent} from "@/models/message.ts";
import {confirmSent, showChatMsg, showRead, showRecall} from "@/models/msg_show_process.ts";
import {User} from "@/models/chat_model.ts";


const websocketUrl = import.meta.env.VITE_WEBSOCKET_URL;

const signalHost = import.meta.env.VITE_SIGNAL_HOST;

const router = useRouter();

const loginStore = useLoginStore()
const contactStore = useContactStore();
const chatStore = useChatStore();

const signalWS = new SignalWS(signalHost);
//注入方法
provide("signalWS", signalWS);

const chatWS = useWebSocket(websocketUrl, (chatData: any) => {
      const msgEvent = chatData.event as MsgEvent;
      const message = chatData.message as ChatMessage;

      if (message) {
        message.isSelf = false;

        contactStore.getChatter(message.chatId, message.isGroup, message.sender).then(chatter => {
          console.debug("show chatMsg ...");
          showChatMsg(message, chatter, chatStore).then();
        });
      } else if (msgEvent) {
        handleActionMsg(msgEvent);
      }
    }
);
//注入方法
provide("chatWS", chatWS);


let loggedIn = getTokenAtStorage() !== null;
console.info(">>> App 挂载了... loggedIn=" + loggedIn);

window.ipcRenderer.on('verify-token', (_, token) => {
  console.debug("ipcRenderer.on verify-token ... ")
  //如果有token，则去验证，如果没有则路由到登录页
  if (token && token.accessToken) {
    setTokenAtStorage(token.accessToken);
    setRefreshTokenAtStorage(token.refreshToken);

    //去调用验证token的接口
    console.debug("调用 验证token有效性接口 to verify token ...")
    LoginApi.checkingAuth().then(resp0 => {
      // console.log("resp0 = ", resp0);
      if (resp0.data) {
        //查询用户信息
        UserApi.findUserById(token.uid).then(resp => {
          // console.log("request getUserInfo resp= ", resp);

          const loginUser = new User({
            uid: resp.data.uid,
            username: resp.data.username,
            nickname: resp.data.nickname,
            avatarUrl: resp.data.avatarUrl
          });
          //存储登录用户信息、token信息
          loginStore.saveUserInfo(loginUser, null);

          chatStore.reloadData(loginUser).then();
          contactStore.refreshContactsGroups().then();
          contactStore.refreshApplyList().then();

          toHome();
        });

        chatWS.connect(token.accessToken); //websocket连接
        signalWS.connect(token.uid); //peer连接
      } else {
        loginStore.clearUserInfo().then();
        toLogin(); //跳转登录页面
      }
    })
  }

})

/**
 * 处理接收的Action信息
 * @param msg
 */
function handleActionMsg(msg: MsgEvent) {
  console.log(">>> 收到事件消息：msg = ", msg)
  switch (msg.action) {
    case E_Action.ACK:
      //消息已经确认发送
      confirmSent(msg, chatStore).then();
      break;
    case E_Action.THE_OTHER_READ:
      console.debug(`msgId=${msg.msgId}消息已读`)
      showRead(msg.msgId, msg.chatId).then()
      break;
    case E_Action.THE_RECALLED:
      showRecall(msg.msgId, msg.chatId).then()
      break;
    case E_Action.RECALL_ALLOW:
      showRecall(msg.msgId, msg.chatId).then()
      break;
    case E_Action.RECALL_FORBID:
      console.log(`消息撤回失败 msgId = ${msg.msgId}`)
      break;
    default:
      console.warn(`action=${msg.action}: do nothing`)
  }
}

/**
 * 路由到主页面
 */
const toHome = () => {
  router?.replace({path: '/'})
}
const toLogin = () => {
  router?.replace({path: '/login'})
}
</script>

<style scoped>
</style>
